package com.kapcb.async.executor.timer;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * <a>Title: SystemClock </a>
 * <a>Author: Kapcb <a>
 * <a>Description: 用于解决高并发下 System.currentTimeMillis 卡顿 <a>
 *
 * @author Kapcb
 * @version 1.0
 * @date 2024/5/11 22:23
 * @since 1.0
 */
public class SystemClock {

    private final int period;

    private final AtomicLong now;

    private static class InstantHolder {
        private static final SystemClock INSTANT = new SystemClock(1);
    }

    private SystemClock(int period) {
        this.period = period;
        this.now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }

    private static SystemClock instance() {
        return InstantHolder.INSTANT;
    }

    private void scheduleClockUpdating() {
        ScheduledExecutorService scheduled = Executors.newSingleThreadScheduledExecutor(runnable -> {
            Thread thread = new Thread(runnable, "System Clock");
            thread.setDaemon(true);
            return thread;
        });

        scheduled.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
    }

    private long currentTimeMillis() {
        return now.get();
    }

    /**
     * 用来替换原来的 System.currentTimeMillis()
     * @return
     */
    public static long now() {
        return instance().currentTimeMillis();
    }
}
